//
//  YCSplitScreenView.m
//  Test
//
//  Created by Sheng long on 16/2/1.
//  Copyright © 2016年 Sheng long. All rights reserved.
//

#import "YCSplitScreenView.h"
#import <Masonry/Masonry.h>

#define Tags(__tag)     (__tag+20)

typedef UIView* (^TableSelected)(NSInteger index);

@interface YCSplitScreenView ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,copy) TableSelected tableSelect;

@end

@implementation YCSplitScreenView

- (void)dealloc{
#ifdef DEBUG
    NSLog(@"dealloc -- %@",self.class);
#endif
}

- (void)showView:(UIView *(^)(NSInteger index))selected{
    self.selectedIndex = -1;
    self.tableSelect = selected;
    
    UITableView *table = [UITableView new];
    self.mainTable = table;
    [self addSubview:table];
    table.delegate = self;
    table.dataSource = self;
    table.separatorColor = [UIColor clearColor];
    table.backgroundColor = [UIColor clearColor];
    table.bounces = NO;
    [table registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [table mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.mas_equalTo(0);
        make.width.mas_equalTo(self.titleWidth);
    }];
}

- (void)setSelectedIndex:(NSInteger)selectedIndex{
    _selectedIndex = selectedIndex;
    NSIndexPath *ip = [NSIndexPath indexPathForRow:selectedIndex inSection:0];
    [self.mainTable deselectRowAtIndexPath:ip animated:NO];
    
    if (self.tableSelect) {
        for (UIView *view in self.subviews) {
            if (view.tag>=Tags(0)) {
                view.hidden = YES;
            }
        }
        
        UIView *view = [self viewWithTag:Tags(selectedIndex)];
        if (!view) {
            view = self.tableSelect(selectedIndex);
            view.tag = Tags(selectedIndex);
            [self addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(self.titleWidth);
                make.right.top.bottom.mas_equalTo(0);
            }];
        }
        view.hidden = NO;
    }
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.titleArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.textLabel.text = self.titleArray[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return self.titleHeight>0?self.titleHeight:44;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    [self.mainTable reloadData];
    self.selectedIndex = indexPath.row;
}

@end
